package com.aiwiown.snackmq.broker.handler.console;

import com.aiwiown.snackmq.broker.auth.AuthorizationService;
import com.aiwiown.snackmq.cluster.metadata.MetadataManager;
import com.aiwiown.snackmq.cluster.raft.closeure.SnackMQApplyClosure;
import com.aiwiown.snackmq.common.auth.Permission;
import com.aiwiown.snackmq.common.handler.RequestContext;
import com.aiwiown.snackmq.common.message.Message;
import com.aiwiown.snackmq.common.message.MessageType;
import com.aiwiown.snackmq.common.serialization.JsonSerializer;
import com.aiwiown.snackmq.common.serialization.SerializerFactory;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SetRolePermissionsHandler extends AbstractLeaderRequiredConsoleHandler {

    private final JsonSerializer serializer = SerializerFactory.getJsonSerializer();

    public SetRolePermissionsHandler(MetadataManager metadataManager, AuthorizationService authorizationService) {
        super(metadataManager, authorizationService);
    }

    @Override
    public MessageType getMessageType() {
        return MessageType.SET_ROLE_PERMISSIONS_REQUEST;
    }

    @Override
    protected void doHandle(RequestContext ctx, Message request) {
        try {
            // 2. 解析参数
            String roleName = request.getProperty("roleName");
            String permissionsJson = request.getProperty("permissions");

            if (roleName == null || roleName.isEmpty() || permissionsJson == null) {
                SnackMQApplyClosure.sendErrorResponse(ctx, request, "Role name and permissions (as JSON string) are required.");
                return;
            }

            // 3. 反序列化权限列表
            java.lang.reflect.Type listType = new com.google.gson.reflect.TypeToken<java.util.List<Permission>>() {}.getType();
            java.util.List<Permission> permissions = serializer.deserialize(permissionsJson.getBytes(), listType);

            // 4. 提议到 Raft
            log.info("Proposing to set {} permissions for role '{}'", permissions.size(), roleName);
            SnackMQApplyClosure closure = new SnackMQApplyClosure(request, ctx, null);
            metadataManager.setRolePermissions(roleName, permissions, closure);
        } catch (Exception e) {
            log.error("Error processing set role permissions request", e);
            SnackMQApplyClosure.sendErrorResponse(ctx, request, "Internal server error: " + e.getMessage());
        }
    }
}